package com.xyy.saas.payment.controller;

import com.xyy.saas.payment.adpater.RouteManager;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.api.PaymentOrderApi;
import com.xyy.saas.payment.cores.bo.FrozenBo;
import com.xyy.saas.payment.cores.bo.QueryResultBo;
import com.xyy.saas.payment.cores.bo.SeparateAccountsBo;
import com.xyy.saas.payment.cores.bo.UnfrozenBo;
import com.xyy.saas.payment.cores.param.ProfitSharingParam;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.cores.vo.SeparateAccountFromUserVo;
import com.xyy.saas.payment.dao.model.PrePayOrder;
import com.xyy.saas.payment.merchant.core.dto.QueryTransactionStatusDto;
import com.xyy.saas.payment.merchant.core.dto.FrozenDto;
import com.xyy.saas.payment.merchant.core.dto.UnfrozenDto;
import com.xyy.saas.payment.payment.core.service.PrePayOrderService;
import com.xyy.saas.payment.payment.core.service.ProfitSharingService;
import com.xyy.saas.payment.util.HttpClientUtil;
import com.xyy.saas.payment.util.JSONUtils;
import com.xyy.saas.payment.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/qingtan/test")
public class QingtanTestCtrl {
    @Resource
    private ProfitSharingService profitSharingService;
    @Resource
    private PaymentOrderApi paymentOrderApi;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private PrePayOrderService prePayOrderService;
    @Resource
    private RouteManager routeManager;

    @GetMapping("/redisLock")
    public void redisLock(String key) {
        log.info("___________________exits={}", redisUtil.exists(key));
        log.info("___________________setNx={}", redisUtil.setNx(key));
        log.info("___________________get={}", redisUtil.get(key));
        log.info("___________________exits={}", redisUtil.exists(key));
        log.info("___________________setNx={}", redisUtil.setNx(key));
        log.info("___________________get={}", redisUtil.get(key));
        log.info("___________________del={}", redisUtil.del(key));
        log.info("___________________exits={}", redisUtil.exists(key));
        log.info("___________________set={}", redisUtil.set(key, 5L));
        log.info("___________________get={}", redisUtil.get(key));

        try {
            Thread.sleep(5000L);
        }
        catch(InterruptedException e) {
            log.error(e.getMessage(), e);
        }

        log.info("___________________get={}", redisUtil.get(key));
    }

//    /**
//     * 生成待冻结账单
//     * @param businessOrderType
//     * @param startTime
//     * @param endTime
//     * @return
//     */
//    @PostMapping(value = "/genFrozenSettlementOrder")
//    public String genFrozenSettlementOrder(String businessOrderType, String startTime, String endTime) {
//        try {
//            frozenSettlementService.genFrozenSettlementOrder(businessOrderType, DateUtil.sdf1ToDate(startTime), DateUtil.sdf1ToDate(endTime));
//            return "SUCCESS";
//        }
//        catch(Exception ex) {
//            log.error(ex.getMessage() ,ex);
//            return "FAIL";
//        }
//    }

    @PostMapping(value = "/getPrePayOrder")
    public List<PrePayOrder> getPrePayOrder(String businessOrderType, String businessOrderNo) {
        return prePayOrderService.likePrePayOrderByBusinessOrderNo(businessOrderType, businessOrderNo);
    }
//
//    /**
//     * 冻结
//     * @param virtualAccountDto
//     * @return
//     */
//    @PostMapping(value = "/frozenBalance")
//    public String frozenBalance(@RequestBody VirtualAccountDto virtualAccountDto) {
//        try {
//            frozenSettlementService.frozenBalance(virtualAccountDto);
//            return "SUCCESS";
//        }
//        catch(Exception ex) {
//            log.error(ex.getMessage() ,ex);
//            return "FAIL";
//        }
//    }

    @PostMapping(value = "/profitSharing")
    public Object profitSharing(@RequestBody ProfitSharingParam profitsharingParam) throws PaymentException {
        return profitSharingService.profitSharing(profitsharingParam);
    }

    @RequestMapping(value = "/separateAccountFromUser", method = RequestMethod.POST)
    public ResultVO<SeparateAccountsBo> separateAccountFromUser(@RequestBody SeparateAccountFromUserVo separateAccountFromUserVo) {
        log.info("TestController#separateAccountFromUser, separateAccountFromUserVo={}", JSONUtils.toJSON(separateAccountFromUserVo));
        return paymentOrderApi.separateAccountFromUser(separateAccountFromUserVo, StringUtils.EMPTY);
    }

    @PostMapping(value = "/frozenBalance2")
    public FrozenBo frozenBalance(@RequestBody FrozenDto frozenDto) throws PaymentException {
        return routeManager.frozenBalance(frozenDto);
    }

    @PostMapping(value = "/unfrozenBalance2")
    public UnfrozenBo unfrozenBalance(@RequestBody UnfrozenDto unfrozenDto) throws PaymentException {
        return routeManager.unfrozenBalance(unfrozenDto);
    }

//    @PostMapping(value = "/checkTransactionStatus")
//    public QueryResultBo checkTransactionStatus(String businessOrderType, String transactionNo, String tradeType, String accountId) throws PaymentException {
//        return routeManager.queryTransactionStatus(QueryTransactionStatusDto.build(businessOrderType, transactionNo, tradeType, accountId), StringUtils.EMPTY);
//    }

    @PostMapping(value = "/uploadFile")
    public Object uploadFile(String dirPath) throws PaymentException {
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        Map<String, File[]> map = new HashMap<>();

        assert files != null;
        for(File file : files) {
            String fileName = file.getName();


            if(!fileName.contains("jpg") && !fileName.contains("png")) {
                System.out.println("-------ignore " + fileName);
                continue;
            }

            String drugstoreId = fileName.substring(0, fileName.indexOf("-"));
            File[] image = map.computeIfAbsent(drugstoreId, k -> new File[2]);

            if(fileName.contains("正")) {
                image[0] = file;
            }
            else {
                image[1] = file;
            }
        }

        Iterator<String> itr = map.keySet().iterator();

        while(itr.hasNext()) {
            String drugstoreId = itr.next();
            File[] images = map.get(drugstoreId);

            try {
                String front = HttpClientUtil.uploadFile(images[0]);
                String back = HttpClientUtil.uploadFile(images[1]);
                System.out.println(drugstoreId + " " + front + " " + back);
            }
            catch(Exception ex) {
                log.error(ex.getMessage() ,ex);
            }
        }

        return "SUCCESS";
    }
}